class Compiler {
    constructor(vm) {
        this.el = vm.$el
        this.vm = vm
        this.compiler(this.el)
    }
    // 解析指令
    compiler(el) {
        let childNodes = el.childNodes
        Array.from(childNodes).forEach(node => {
            if (this.isTextNode(node)) {
                this.compilerText(node)
            } else if (this.isElementNode(node)) {
                this.compilerElement(node)
            }
            if (node.childNodes && node.childNodes.length) {
                this.compiler(node)
            }
        })
    }
    // 解析元素节点
    compilerElement(node) {
        Array.from(node.attributes).forEach(arrt => {
            let attrName = arrt.name
            if (this.isDirective(attrName)) {
                attrName = attrName.substr(2)
                let key = arrt.value
                this.updater(node, key, attrName)
            }
        })
    }

    updater(node, key, attrName) {
        if (this.isEventDirective(attrName)) {
            this.onUpdater(node, attrName, key)
        } else {
            let updaterFn = this[attrName + 'Updater']
            updaterFn && updaterFn.call(this, node, this.vm[key], key)
        }    
    }
    // v-text
    textUpdater(node, value, key) {
        node.textContent = value
        new Wacther(this.vm, key, newValue => {
            node.textContent = newValue
        })
    }
    // v-modal
    modelUpdater(node, value, key) {
        node.value = value
        new Wacther(this.vm, key, newValue => {
            node.value = newValue
        })

        node.addEventListener('input', () => {
            this.vm[key] = node.value
        })
    }
    // v-html
    htmlUpdater(node, value, key) {
       node.innerHTML = value
       new Wacther(this.vm, key, newValue => {
            node.innerHTML = newValue
        })
    }
    // v-on
    onUpdater(node, attrName, key) {
        let event = attrName.substr(3)
        let handler = this.vm.$options.methods[key]
        if (!handler) {
            console.log('当前函数未定义')
            return
        }
        node.addEventListener(event, handler, false)
    }
    // 解析文本节点
    compilerText(node) {
        let reg = /\{\{(.+?)\}\}/
        let value = node.textContent
        if(reg.test(value)) {
            let key = RegExp.$1.trim()
            node.textContent = value.replace(reg, this.vm[key])

            // 创建watcher 对象，监听对象 更新视图
            new Wacther(this.vm, key, (newValue) => {
                node.textContent = value.replace(reg, newValue)
            })
        }
    }
    // 判断是否是指令
    isDirective(attrname) {
        return attrname.startsWith('v-')
    }
    // 是否是元素节点
    isElementNode(node) {
        return node.nodeType === 1
    }
    // 是否是文本节点
    isTextNode(node) {
        return node.nodeType === 3
    } 
    // 是否是v-on 指令
    isEventDirective(attrname) {
        return attrname.startsWith('on:')
    }
}